const info = require('../../providers/dataAccess').info;
const sys = require('../../providers/dataAccess').sys;
const jwt = require('jsonwebtoken');
const appConfig = require('../../configs/appConfig.js');

const PassportService = function () {
  const _login = async (userName,password) => {

      let accessTokenExpiresIn = 60*60*24*30;

     let szSql = `
        SELECT coreUserId,roleId,userName,appId,nickName,avatarUrl
        FROM cms_accounts
        WHERE userName = ? AND password = ?
     `;
     let rows = await info.query(szSql, [userName,password]);
     if (rows && rows.length) {
          const profile = rows[0];
          const szBearerToken = jwt.sign(profile, appConfig.jwt.secret, {expiresIn: accessTokenExpiresIn});
          profile.accessToken = {
              token: szBearerToken,
              expiresIn: accessTokenExpiresIn
          };
          szSql = 'SELECT * FROM apps WHERE id = ?';
          rows = await sys.query(szSql,[profile.appId]);
          profile.appInfo = rows && rows[0] ? rows[0] : null;

          return profile;
     } else {
       return "";
     }
  };

  return {
      login: _login
  }
}();

module.exports = PassportService;
